package com.zui.util.jms;

import java.io.Serializable;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.support.JmsGatewaySupport;
import org.springframework.mail.MailMessage;
import org.springframework.mail.SimpleMailMessage;

import com.zenith.yasoo.party.Person;
import com.zui.util.mail.MailManager;

/**
 * This is a jms gateway implementation to the MailManager class. 
 * This implementation will send mail asynchronously to a message queue.
 * using apache-activemq4.1.1 for message broker.
 * @author zzuizui
 */
public class MailManagerJmsImpl extends JmsGatewaySupport implements MailManager {
	protected transient final Log log = LogFactory.getLog(getClass());
	private String destinationQueueName;

	public void setDestinationQueueName(String destinationQueueName) {
		this.destinationQueueName = destinationQueueName;
	}

	public void sendSignupConfirmationMessage(final Person person) {
		getJmsTemplate().send(destinationQueueName, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				ObjectMessage message = null;
				message = session.createObjectMessage(person.getClass());
				message.setObject(person);
				log
						.debug("Mail gateway has sent out the signup confirmation mail message for '"
								+ person.getEmail()
								+ "' to the queue named '"
								+ destinationQueueName);
				return message;
			}
		});
	}

	public void sendMailMessage(final MailMessage mailMessage) {
		getJmsTemplate().send(destinationQueueName, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				ObjectMessage message = null;

				if (mailMessage instanceof DynamicMailMessage) {
					message = session
							.createObjectMessage(DynamicMailMessage.class);
				} else {
					message = session
							.createObjectMessage(SimpleMailMessage.class);
				}
				message.setObject((Serializable) mailMessage);

				log
						.debug("Mail gateway has sent out the mail message to the destination named '"
								+ destinationQueueName
								+ "'\nThe mailMessage object is: "
								+ mailMessage);
				return message;
			}
		});
	}

}
